﻿package 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;	
	import flash.events.Event;
	import flash.text.TextField;
	import org.papervision3d.cameras.Camera3D;
	import org.papervision3d.core.effects.BitmapLayerEffect;
	import org.papervision3d.core.geom.Pixels;
	import org.papervision3d.core.geom.renderables.Pixel3D;
	import org.papervision3d.render.BasicRenderEngine;
	import org.papervision3d.scenes.Scene3D;
	import org.papervision3d.view.layer.BitmapEffectLayer;
	import org.papervision3d.view.Viewport3D;
	
	/*
	 * coded by moka 2009 / 06/ 20 
	 * name : moka's PixelPlay
	 */
	
	public class Main extends Sprite 
	{		
		private var scene:Scene3D;
		private var camera:Camera3D;
		private var viewport:Viewport3D;
		private var render:BasicRenderEngine;
		private var pixelLayer:BitmapEffectLayer;
		private var pixels:Pixels;
		
		// 貼圖的紋理
		[Embed(source = 'moka.gif')]
		private var EmbeddedImage:Class;
		private var image:Bitmap;

		public function Main():void 
		{		
			// Class 類別隱式轉換成 Bitmap 類別
			image = new EmbeddedImage(); 
			
			// 設定場景不變形
			stage.scaleMode = "noScale"; 
			
			// Scene3D 用來組織場景母子關係樹狀架構
 			scene = new Scene3D();

			// Camera3D 為 3D 場景可視範圍設定
			camera = new Camera3D();
			
			// Viewport3D 用在呈現於 flash 場景(其類別繼承Sprite)
			viewport = addChild(new Viewport3D(640, 480)) as Viewport3D;
			
			// 用以渲染 3D 場景之類別
			render = new BasicRenderEngine();
			
			// 新增 pixelLayer 讓 pixel 繪製上去
			pixelLayer = new BitmapEffectLayer(viewport, 640, 480);
			pixelLayer.clearBeforeRender = true; // 清除畫面再繪製
			viewport.containerSprite.addLayer(pixelLayer); // 讓 Pixels 可以被繪製出來
			pixels = scene.addChild(new Pixels(pixelLayer)) as Pixels; // Pixels 物件加入場景
			
			// 建立粒子陣列並把每個粒子設定座標 ( moka.gif 128 X 128 )
			var width:uint = 128;
			var height:uint = 128;
			var total:uint = width*height;
			var gap:uint = 8; // 粒子間距
						
			for(var i:uint = 0; i < total; i++)
			{
				pixels.addPixel3D(new Pixel3D(image.bitmapData.getPixel32(i % width,Math.floor(i / width)), 0, 0, 0));
				pixels.pixels[i].x = i % width *gap-width/2*gap;
				pixels.pixels[i].y = Math.floor(i / width)*gap - height/2*gap;
				pixels.pixels[i].z = image.bitmapData.getPixel(i % width,Math.floor(i / width))>>16;
			}
			
			// 註冊 ENTER_FRAME 事件
			addEventListener(Event.ENTER_FRAME, onProcess);			

			// Moka's work 2009
			(addChild(new TextField()) as TextField).htmlText = "<font color='#FFFFFF'>Moka's work 2009</font>"; 
		}		
		
		private function onProcess(e:Event):void {	
			// 旋轉 pixels 物件
			pixels.rotationX = mouseY;
			pixels.rotationZ = mouseX;
			
			// 渲染 3D 場景
			render.renderScene(scene, camera, viewport);
		}
	}	
}